const formidable = require('formidable');
// const fs = require('fs');
const util = require('util');
const path = require('path');

exports.upload = function upload(req, res) {
  const form = new formidable.IncomingForm();
  form.encoding = 'utf-8';
  form.uploadDir = path.join(process.cwd(), 'examples');
  form.multiples = true;
  form.keepExtensions = true;
  form.maxFieldsSize = 1024 * 1024;
  const files = {};
  const fields = {};
  form
  .on('error', (err) => {
    res.writeHead(400);
    res.end(err);
  })
  .on('field', (field, value) => {
    fields[field] = value;
  })
  .on('file', (field, file) => {
    files[field] = file;
  })
  .on('end', () => {
    res.writeHead(200, { 'content-type': 'text/plain' });
    res.end(util.inspect({ filed: fields, file: files }));
  });
  form.parse(req);
};
